<template>
	<div class="content">
		<div class="pageSearchView">
			<SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">列表信息 <el-icon>
						<house-icon />
					</el-icon>
				</div>
				<div class="pageTableButView">
					<el-button :icon="Plus" @click="handleAdd">新建</el-button>
					<!-- 添加列按钮 -->
					<el-button :icon="Plus" @click="showAddColumnDialog = true" type="primary">表头列配置</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)" row-key="id"
				:loading="isLoading" header-cell-class-name="witheTableHeader" @expand-change="handleExpandChange">
				<el-table-column type="expand">
					<template #default="scope">
						<!--            子级列表-->
						<div m="4">
							<el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
								style="width: 85vw" header-cell-class-name="blueTableHeader">
								<el-table-column type="index" label="序号" width="55" align="center" />
								<el-table-column prop="toolRegisterCode" min-width="150" label="工装编码" align="center" />
								<el-table-column prop="toolRegisterName" min-width="200" label="工装名称" align="center" />
								<el-table-column prop="no" min-width="200" label="模具代号" align="center" />
							</el-table>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="序号" align="center" width="70">
					<template #default="scope"> {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1
						}} </template>
				</el-table-column>
				<el-table-column prop="name" label="工装类型名称" align="center" min-width="150" />
				<el-table-column prop="toolingCode" label="工装类型编码" align="center" min-width="150" />
				<!--        <el-table-column prop="toolingInventoryType" label="工装来源" align="center">-->
				<!--          <template #default="scope">-->
				<!--            {{ getTypeName(scope.row.toolingInventoryType) }}-->
				<!--          </template>-->
				<!--        </el-table-column>-->
				<el-table-column prop="toolingAttributes" label="工装属性" align="center" width="100"
					:formatter="toolingAttributesFormatter" />
				<el-table-column prop="activate" label="是否启用" align="center">
					<template #default="scope">
						<div v-if="scope.row.activate == 1">是</div>
						<div v-else>否</div>
					</template>
				</el-table-column>
				<!-- 动态列渲染 -->
				<el-table-column v-for="col in columns" :key="col.tableKey" :prop="col.tableKey" :label="col.tableChineseKey"
					align="center" />
				<el-table-column label="操作" align="center" fixed="right" width="280">
					<template #default="scope">
						<el-button @click="binding(scope.row)" size="small" plain text :icon="Edit">绑定工装</el-button>
						<el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
						<el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background v-model:current-page="paginationParams.current"
					v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next" :total="pageTotal"
					@size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 弹窗表单 -->
		<el-dialog v-model="showCrud" :title="crudTitle" width=500>
			<el-form :model="formData" label-width="130px" ref="ruleFormRef" :rules="rules">
				<el-row>
					<el-form-item label="工装类型名称" required prop="name">
						<el-input v-model="formData.name" placeholder="请输入工装类型名称" style="width: 300px" />
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="工装类型编码" required prop="toolingCode">
						<el-input v-model="formData.toolingCode" placeholder="请输入工装类型编码" style="width: 300px" />
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="工装属性" required prop="toolingAttributes">
						<el-select v-model="formData.toolingAttributes" placeholder="请选择工装属性" style="width: 300px">
							<el-option v-for="item in attributesOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
						<!--            <el-input v-model="formData.toolingType" placeholder="请输入工装类型" style="width: 300px" />-->
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="是否启用" required prop="activate">
						<el-select v-model="formData.activate" placeholder="请选择是否启用" style="width: 300px">
							<el-option :key="1" label="是" :value="true" />
							<el-option :key="0" label="否" :value="false" />
						</el-select>
					</el-form-item>
				</el-row>
				<el-row>
					<!-- 动态字段在弹窗中渲染 -->
					<el-form-item v-for="col in columns" :key="col.tableKey" :label="col.tableChineseKey" :prop="col.tableKey">
						<el-input v-model="formData[col.tableKey]" :placeholder="`请输入${col.tableChineseKey}`"
							style="width: 300px" />
					</el-form-item>
				</el-row>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave">保存</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 动态添加列的对话框 -->
		<el-dialog v-model="showAddColumnDialog" title="管理列信息">
			<!-- 表格增删改查 -->
			<el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
				style="margin-bottom: 20px;">新建列 </el-button>
			<el-table :data="columns">
				<el-table-column prop="tableChineseKey" label="列名称" align="center" />
				<el-table-column prop="tableKey" label="列编码" align="center" />
				<el-table-column label="操作" align="center">
					<template #default="scope">
						<el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
						<el-button @click="deleteColumn(scope.row, scope.$index)" size="small" type="danger" icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<el-button @click="showAddColumnDialog = false">关闭</el-button>
			</template>
		</el-dialog>
		<!-- 动态添加列的对话框 -->
		<el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
			<el-form>
				<el-form-item label="列名称">
					<el-input v-model="newColumn.tableChineseKey" placeholder="请输入列名称" />
				</el-form-item>
				<el-form-item label="列Key">
					<el-input v-model="newColumn.tableKey" placeholder="请输入列Key" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showAddColumnDialog2 = false">取消</el-button>
				<el-button type="primary" @click="addColumn">确定</el-button>
			</template>
		</el-dialog>
		<el-dialog v-model="showBingding" title="绑定工装" width="90%">
			<div class="twoTableView">
				<el-table ref="myTable" :data="equipmentData" style="width: 49%" height="500px" row-key="id" border
					@selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column type="index" label="序号" width="55" align="center" />
					<el-table-column prop="toolRegisterCode" min-width="150" label="工装编码" align="center" />
					<el-table-column prop="registerName" min-width="200" label="工装名称" align="center" />
					<el-table-column prop="no" min-width="200" label="模具代号" align="center" />
				</el-table>
				<el-table ref="table" :data="multipleSelection" style="width: 49%" height="500px" row-key="id" border>
					<el-table-column type="index" label="序号" width="55" align="center" />
					<el-table-column prop="toolRegisterCode" min-width="150" label="工装编码" align="center" />
					<el-table-column prop="registerName" min-width="200" label="工装名称" align="center" />
					<el-table-column prop="no" min-width="200" label="模具代号" align="center" />
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showBingding = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit()">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue'
import { useToolData } from '@/hooks/baseData/toolingType'
import axiosInstance from '@/utils/http/api'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'; // 假设使用 Element Plus
import { computed, ref } from 'vue'

const {
	searchParam,
	paginationParams,
	pageTotal,
	paginatedData,
	searchFields,
	handleSearch,
	handleSizeChange,
	handleCurrentChange,
	addTool,
	deleteTool,
	isLoading,
	ruleFormRef,
	rules,
	formData
} = useToolData();


const attributesOptions = ref([
	{
		label: '工装',
		value: 1
	}, {
		label: '模具',
		value: 2
	}, {
		label: '检具',
		value: 3
	}, {
		label: '刀具',
		value: 4
	}
]);

const toolingAttributesFormatter = (e) => {
	const attribute = attributesOptions.value.find(option => option.value == e.toolingAttributes);
	return attribute ? attribute.label : '';
};

const getTypeName = (type: string) => {
	const name = typeList.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};
onMounted(() => {
	getColumnsList();
});
// 动态列和新列的数据
const columns = ref([
	{ tableChineseKey: '自定义列1', tableKey: 'tableKey', visible: true },
	{ tableChineseKey: '自定义列2', tableKey: 'tableKey', visible: true }
	// 可添加更多默认列
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref('');
const columnIndexNumber = ref(0);

const newColumn = ref({
	tableChineseKey: '',
	tableKey: '',
	visible: true,
	id: ''
});
// 查询列
const getColumnsList = () => {
	axiosInstance.post('/api/toolRegister/pageByParam',
		{ current: 1, pageSize: 999 }
	).then(res => {
		equipmentData.value = res.data.records
	});

	axiosInstance.post('/api/dynamicTableExtension/getPage',
		{ page: 1, pageSize: 999, tableName: 'toolingType' }
	).then(res => {
		const { data, code, message } = res;
		if (code === 200) {
			console.log(data);
			columns.value = data.records;
		}
	});
};


// 新建列
const addColumn = () => {
	console.log('编辑');

	if (newColumn.value.tableKey && newColumn.value.tableChineseKey) {

		if (columnDialogTitle.value === '新建') {
			axiosInstance.post('/api/dynamicTableExtension/save', {
				'frontendType': 'INPUT',
				'tableName': 'toolingType',
				'tableKey': newColumn.value.tableKey,
				'tableChineseKey': newColumn.value.tableChineseKey
			}).then(res => {
				if (res.code === 200) {
					ElMessage.success('新建列成功');
					getColumnsList();
					// columns.value.push({ ...newColumn.value });
					newColumn.value = { tableKey: '', tableChineseKey: '', visible: true };
					showAddColumnDialog2.value = false;
				}
			});

		} else {
			console.log('编辑');
			axiosInstance.put('/api/dynamicTableExtension/update', {
				'frontendType': 'INPUT',
				'tableName': 'toolingType',
				'tableKey': newColumn.value.tableKey,
				'tableChineseKey': newColumn.value.tableChineseKey,
				'id': newColumn.value.id

			}).then(res => {
				if (res.code === 200) {
					ElMessage.success('修改成功');
					getColumnsList();
					showAddColumnDialog2.value = false;

				}
			});

		}

	}
};
const handleExpandChange = (row: any, expandedRows: any[]) => {
	if (expandedRows.includes(row)) {
		rowChildren(row);
	}
};
const rowChildren = (row: any) => {
	axiosInstance.get('/api/basedataTooling/getToolRegisterById', { params: { toolingId: row.id } }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		paginatedData.value = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data };
			}
			return item;
		});
	});
};
const showBingding = ref(false);
const equipmentData = ref([]);
const multipleSelection = ref([]);
const handleSelectionChange = (e) => {
	const list = JSON.parse(JSON.stringify(e));
	for (const item of list) {
		item.equipmentId = item.id;
	}
	multipleSelection.value = list;
};

const handleSubmit = () => {
	// if (multipleSelection.value.length == 0) {
	// 	ElMessage.error('请选择数据！');
	// 	return;
	// }

	const ids = multipleSelection.value.map(item => item.id)
	const param = {
		toolingId: rowInfo.value.id,
		ids
	}

	axiosInstance.put('/api/basedataTooling/updateToolRegister', param).then(res => {
		if (res.code != 200) {
			ElMessage.error(res.message);
			return false;
		}
		ElMessage.success('绑定成功');
		showBingding.value = false;
		paginatedData.value = []
		handleSearch()
	});
};
const rowInfo = ref({});
const myTable = ref<TableInstance | null>(null); // 初始化为null
const binding = (row: any) => {
	rowInfo.value = row
	multipleSelection.value = []
	if (myTable.value) {
		myTable.value.clearSelection();
	}
	showBingding.value = true;
	axiosInstance.get('/api/basedataTooling/getToolRegisterById', { params: { toolingId: row.id } }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const list = res.data
		for (const item of equipmentData.value) {
			for (const items of list) {
				if (item.toolRegisterCode == items.toolRegisterCode) {
					multipleSelection.value.push(item)
					myTable.value.toggleRowSelection(
						item,
						true
					)
				}
			}
		}
	});
};


// 编辑列
const editColumn = (row: any, index: number) => {
	columnIndexNumber.value = index;
	columnDialogTitle.value = '编辑';
	showAddColumnDialog2.value = true;
	newColumn.value.tableChineseKey = row.tableChineseKey;
	newColumn.value.tableKey = row.tableKey;
	newColumn.value.id = row.id;
};

// 删除列
const deleteColumn = (row: any, index: number) => {
	axiosInstance.delete('/api/dynamicTableExtension/delete', {
		data: {
			ids: [row.id]
		}
	}).then(res => {
		if (res.code === 200) {
			getColumnsList();
			ElMessage.success('修改成功');

		}
	});
	// columns.value.splice(index, 1);
};

const typeList = ref([
	{ label: '采购入库', value: '0' },
	{ label: '自制入库', value: '1' },
	{ label: '其他', value: '2' }
]);
const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
	return isEdit.value ? '编辑' : '新建';
});


// 新建记录
const handleAdd = () => {
	isEdit.value = false;
	console.log(formData.value, ' formData.value');
	formData.value = {};
	showCrud.value = true;
};


// 编辑记录
const handleEdit = (row: any) => {
	isEdit.value = true;
	formData.value = { ...row };
	showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await deleteTool(row.id);
	}).catch(() => {
	});
};


// 保存记录
const handleSave = async () => {
	const formDataObject = columns.value.reduce((acc, col) => {
		acc[col.tableKey] = formData.value[col.tableKey];
		return acc;
	}, {});
	console.log(formDataObject);
	formData.value.extension = formDataObject;
	await addTool(formData.value, (() => {
		showCrud.value = false;
	}));
};


</script>
<style scoped>
.twoTableView {
	display: flex;
	justify-content: space-between;
}
</style>
